import { getCenter } from '../../../../mapUtils/GeometryUtil';
import DistrictList from '../../../../constant/DistrictList';
import ITool from '../ITool';

/**
 * 行政区划工具箱
 * @implements {ITool}
 */
class DistrictTool extends ITool {
  constructor(_top, _impl) {
    super(_top, _impl);
    this.name = 'DistrictTool';
    this.desc = '行政区划工具箱';
  }

  onAdd() {
    super.onAdd();
  }

  onRemove() {
    super.onRemove();
  }

  /**
   * 省市区名称转拼音首字母
   * @param {Array} cityStr ["省", "市", "区"]
   */
  transformPinYin(cityStr) {
    let pinyin = '';
    cityStr.forEach((item) => {
      // 自动生成区域编号的时候
      // 比如鼓楼区  去匹配gl
      // 因为全国 有很多个鼓楼区  就循环查找的时候  找到了多个gl
      // 编号就变成FJ - FZ - GL - GL - GL - GL
      let found = DistrictList.find((citem) => item === citem[1] || item === citem[1] + citem[6]);
      pinyin += (found ? found[4].toUpperCase() : '') + '-';
    });
    pinyin = pinyin.substring(0, pinyin.length - 1);
    return pinyin;
  }

  /**
   * 查询图形所在行政区划
   * @param {geometry} geometry 图形坐标
   */
  async searchByLocation(geometry) {
    let districtTask = new SGMap.DistrictTask();
    let result = await districtTask.searchByLocation({
      location: getCenter(geometry)
    });
    return result;
  }

  /**
   * 获取省市区名称
   * @param {Array} geometry 地理坐标
   */
  async getRegionName(geometry) {
    let result = await this.searchByLocation(geometry);
    let arr = [];
    result.forEach((item) => {
      arr.push(item.name.substr(0, item.name.length - 1));
    });
    return arr;
  }

  /**
   * 获取省市区编号
   * @param {Array} geometry 地理坐标
   */
  async getRegionCode(geometry) {
    let result = await this.searchByLocation(geometry);
    let arr = [];
    result.forEach((item) => {
      arr.push(item.name.substr(0, item.name.length - 1));
    });
    return this.transformPinYin(arr);
  }

  /**
   * 查询行政区划详细信息
   * @param {String} keyword 行政区划名称或编码
   * @param {Number} subdistrict 返回下级行政区级数
   * @param {Boolean} extension 是否返回行政区边界坐标
   */
  async searchDistrict(keyword, subdistrict, extension) {
    let districtTask = new SGMap.DistrictTask();
    let result = await districtTask.searchDistrict({
      keyword: keyword,
      subdistrict: subdistrict,
      extension: extension
    });
    if (extension) {
      result.forEach((item) => {
        let shape = item.shape;
        if (shape.type === 'Polygon') {
          shape.coordinates[0] = districtTask.decode(shape.coordinates[0]);
        } else {
          shape.coordinates.forEach((coordinate) => {
            coordinate[0] = districtTask.decode(coordinate[0]);
          });
        }
        item.bbox = districtTask.decode(result[0].bbox);
      });
    }
    return result;
  }
}

export default DistrictTool;